package net.dominatingapps.readcalendar;

import java.util.Date;
import java.util.Calendar;
import java.util.HashSet;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;

public class ReadCalendar {

	private static String readCalendarName = "Tony Meehan";
	private static HashSet<String> events = new HashSet<String>();
	
	public static HashSet<String> readCalendar(Context context) {
		
		ContentResolver contentResolver = context.getContentResolver();
		
		// Fetch a list of all calendars synced with the device, their display names and whether the
		// user has them selected for display.
		// 2.1: "content://calendar/calendars"
		// 2.2: "content://com.android.calendar/calendars
		
		final Cursor cursor = contentResolver.query(
				Uri.parse("content://com.android.calendar/calendars"),
				(new String[] { "_id", "displayName", "selected" }), null, null, null);
		
		// For a full list of available columns see http://tinyurl.com/yfbg76w
		
		String cid = null;
		
		/*
		 * Search through all calendars looking for readCalendarName.
		 */
		while (cursor.moveToNext()) {

			final String _id = cursor.getString(0);
			final String displayName = cursor.getString(1);
			
			if (displayName.equals(readCalendarName)) 
			{
				cid = _id;
				break;
			}
		}
		
		if (cid != null)
		{
			Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
			long now = new Date().getTime();
			
			ContentUris.appendId(builder, now - DateUtils.WEEK_IN_MILLIS);
			ContentUris.appendId(builder, now + DateUtils.WEEK_IN_MILLIS);
	
			Cursor eventCursor = contentResolver.query(builder.build(),
					new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + cid,
					null, "startDay ASC, startMinute ASC"); 
			
			// For a full list of available columns see http://tinyurl.com/yfbg76w
	
			while (eventCursor.moveToNext()) {
				final String title = eventCursor.getString(0);
				final Date begin = new Date(eventCursor.getLong(1));

				final Calendar calEvent = Calendar.getInstance();
				
				calEvent.setTime(begin);
				
				final String[] days = new String[] { null, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
				final String[] am_pm = new String[] { "AM", "PM" };
				
				final String event = new String(title + " on " + days[calEvent.get(Calendar.DAY_OF_WEEK)] + " at " + calEvent.get(Calendar.HOUR) + " " + am_pm[calEvent.get(Calendar.AM_PM)]);
				
				System.out.println(event);
				
				events.add(event);
				
			}
		}
		
		return events;
	}
}
